$(function() {
  var htmlGet = decodeURI(location.search)
  var productId = getNum(htmlGet)

  function getNum(str) {
    // console.dir(/\d+/.exec(str));
    //exec()  返回一个数组，其中存放匹配的结果。如果未找到匹配，则返回值为 null
    if (!str || str.length == 0) {
      return "";
    } else {
      var ret = /\d+/.exec(str);
      if (!ret) {
        return "";
      }
      return parseInt(/\d+/.exec(str)[0]);
    }
  }
  // console.log(productId)
  $.ajax({
    url: "http://193.112.55.79:9090/api/getproduct",
    type: "get",
    data: { productid: productId },
    dataType: "json",
    success: function(res) {
      // console.log(res)
      var productStr = template('getProductById', res)
        // console.log(productStr)
      $('#product_comm_title').before(productStr)
      var cataId = res.result[0].categoryId
      console.log(cataId)
      var pdName = res.result[0].productName.split(" ")[0]
        // console.log(pdName)
      $('.breadcrumb li:eq(2)').text(pdName)
      $.ajax({
        url: "http://193.112.55.79:9090/api/getcategorybyid",
        type: "get",
        dataType: "json",
        data: { categoryid: cataId },
        success: function(data) {
          console.log(data)
          var product_name_str = template('product_name', data)
            // console.log(product_name_str)
          $('.breadcrumb li:eq(1)').html(product_name_str)
        }
      })
    }
  })
  $.ajax({
      url: "http://193.112.55.79:9090/api/getproductcom",
      type: "get",
      data: { productid: productId },
      dataType: "json",
      success: function(res) {
        // console.log(res)
        var commStr = template('comment', res)
        $('.product_comm_content ul').html(commStr)
      }
    })
    //返回首页
  $('.btn-back').on('click', function() {
      $(this).attr('href', '../index.html');
    })
    //返回顶部
  $('.footer_top .back').on('click', function() {
    var timeId = setInterval(function() {
      var target = 0;
      var leader = scroll().scrollTop;
      leader = leader + (target - leader) / 10;
      scrollTo(0, leader);
      if (leader == target) {
        clearInterval(timeId);
      }
    })
  })

  function scroll() {
    return {
      scrollTop: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
      scrollLeft: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
    }
  }
})